import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  /*
  * 正常流程如下:主要有两大点token和role
  * 1.用户登录获得token
  * 2.根据token获取role角色和用户信息
  * 3.通过role权限获取动态路由列表
  * 4.设置动态权限列表
  * */
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)
  // determine whether the user has logged in
  // const hasToken = getToken()

  /* 是否需要登录，不需要登录默认给个token 此配置在src/settings.js文件配置*/
  const defaultSettings = require('@/settings.js')
  let hasToken = ''
  if (defaultSettings.isNeedLogin) {
    hasToken = getToken()
  } else {
    hasToken = 'defaultToken'
  }
  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      // 进度条
      NProgress.done()
    } else {
      const hasRoles = store.getters.roles && store.getters.roles.length > 0
      if (hasRoles) { // admin
        next()
      } else {
        try {
          // 1.获取用户信息
          await store.dispatch('user/getInfo')
          // 2.获取路由列表（用于权限）
          const accessRoutes = await store.dispatch('permission/generateRoutes')
          router.addRoutes(accessRoutes)
          next({ ...to, replace: true })
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // 重置页面的缓存
  // store.commit("tagsView/M_RESET_CACHED_VIEW",["VehicleTracking"])
  // finish progress bar
  NProgress.done()
})
